/*
 * Copyright 2011 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.ritesdk.rite4qa;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import edu.cmu.lti.ritesdk.FileUtils;

public class FileUtilsForRITE4QA {

  private static Pattern pTopic = Pattern.compile("<QA>.+?</QA>", Pattern.DOTALL);
  
  public static Map<String,Topic> loadTopics( File file, String lang ) {
    Map<String,Topic> topics = new LinkedHashMap<String,Topic>();
    try {
      Pattern pQ = Pattern.compile("<Q LANG=\""+lang+"\" QID=\"(.+?)\">(.+?)</Q>");  
      Pattern pA = Pattern.compile("<A LANG=\""+lang+"\" DOCNO=\"(.+?)\">(.+?)</A>");
      
      String content = FileUtils.readStringFromFile(file);
      Matcher mTopic = pTopic.matcher(content);
      while (mTopic.find()) {
        String qBlock = mTopic.group();
        Matcher mQ = pQ.matcher(qBlock);
        String question;
        String qid;
        if (mQ.find()) {
          qid = mQ.group(1);
          question = mQ.group(2);
          Matcher mA = pA.matcher(qBlock);
          List<Answer> answers = new ArrayList<Answer>();
          while ( mA.find() ) {
            answers.add( new Answer( mA.group(2).trim(), mA.group(1).trim() ) );
          }
          Topic topic = new Topic( qid, question, answers );
          topics.put(qid, topic);
        }
      }
    } catch (Exception e) {
      System.out.println("ERROR: Problem occurred while loading the CLQA gold standard "+file.getAbsolutePath());
    }
    return topics;
  }
  
}
